# -*- coding: utf-8 -*-
# @Author  : caiweichao
# @explain : 读取excel里的测试用例

import openpyxl

from Commons.util.logs import Log
from ConfigFile import contants_file


class ReadExcel:
    def __init__(self):
        try:
            self.file_name = contants_file.TEST_DATA_PATH + 'TestCase.xlsx'
            Log.debug(f'打开测试用例数据文件：{self.file_name}')
            self.workbook = openpyxl.load_workbook(filename=self.file_name)
        except Exception:
            Log.error(f'打开测试用例数据文件异常{Exception}')
            raise Exception("文件打开异常请检查！")

    # 读取指定sheet页的数据放入data对象
    def getSheetDatas(self, sheetName: str) -> list[dict]:
        allDatas = list(self.workbook[sheetName].rows)
        # 测试用例表头集合
        dataTitle: list = [title.value for title in allDatas[0]]
        # 将第一行之后的数据解析后和第一行组装为测试用例
        datas = [dict(zip(dataTitle, [data.value for data in datas])) for datas in
                 allDatas[1:]]
        return datas

    # 获取cases的标题
    @staticmethod
    def getCaseTitle(testCases: list[dict], key="case_title") -> list:
        """
        通过指定的key获取用例集合中的内容，默认返回用例的标题
        :param testCases: 用例集合list[dict]
        :param key: 用例数据中对应的键
        :return: 键对应的值
        """
        caseTitle = [caseTitle.get(key) for caseTitle in testCases]
        return caseTitle

    def getTestCases(self, sheetNmae:str) -> dict:
        """
        获取全部的测试用例数据
        :param sheetNmae: 传入指定的excel用例集名称
        :return: 返回用例合集 caseTitle 和 caseDatas
        """

        cases = {
            "caseTitle": self.getCaseTitle(testCases=self.getSheetDatas(sheetNmae)),
            "caseDatas": self.getSheetDatas(sheetNmae)
        }
        return cases


if __name__ == '__main__':
    cases = ReadExcel().getTestCases(sheetNmae='OederControl')
    for x in cases.get('caseTitle'):
        print(x)
    for y in cases.get('caseDatas'):
        print(y)
